package cn.dm;

import cn.dm.example.threadLocal.RequestHolder;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
public class HttpFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // request.getSession().getAttribute("user"); // 以前写法
        // 打印当前线程ID和当前请求
        log.info("do filter, {}, {}", Thread.currentThread().getId(), request.getServletPath());
        // 调用自定义的 RequestHolder 类,将 id 加入到 ThreadLocal 中
        RequestHolder.add(Thread.currentThread().getId());
        // 继续执行剩余的过滤链
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
